import { Module, ActionContext } from 'vuex';

interface UserState {
  token: string | null;
  username: string | null;
  name: string | null;
  id: number | null;
}

const state: UserState = {
  token: null,
  username: null,
  name: null,
  id: null,
};

const mutations = {
  setToken(state: UserState, token: string) {
    state.token = token;
  },
  setUsername(state: UserState, username: string) {
    state.username = username;
  },
  setName(state: UserState, name: string) {
    state.name = name;
  },
  setId(state: UserState, id: number) {
    state.id = id;
  },
};

const actions = {
  login(
    { commit }: ActionContext<UserState, any>, 
    payload: { token: string; username: string; name: string; id: number }
  ) {
    commit('setToken', payload.token);
    commit('setUsername', payload.username);
    commit('setName', payload.name);
    commit('setId', payload.id);
    localStorage.setItem('token', payload.token);
    localStorage.setItem('username', payload.username);
    localStorage.setItem('name', payload.name);
    localStorage.setItem('id', payload.id.toString());
  },
  logout({ commit }: ActionContext<UserState, any>) {
    commit('setToken', null);
    commit('setUsername', null);
    commit('setName', null);
    commit('setId', null);
    localStorage.removeItem('token');
    localStorage.removeItem('username');
    localStorage.removeItem('name');
    localStorage.removeItem('id');
  },
  loadLocalStorage({ commit }: ActionContext<UserState, any>) {
    const token = localStorage.getItem('token');
    const username = localStorage.getItem('username');
    const name = localStorage.getItem('name');
    const id = localStorage.getItem('id');
    if (token) {
      commit('setToken', token);
    }
    if (username) {
      commit('setUsername', username);
    }
    if (name) {
      commit('setName', name);
    }
    if (id) {
      commit('setId', parseInt(id, 10));
    }
  },
};

const getters = {
  isLoggedIn(state: UserState): boolean {
    return !!state.token;
  },
  getUsername(state: UserState): string | null {
    return state.username;
  },
  getName(state: UserState): string | null {
    return state.name;
  },
  getId(state: UserState): number | null {
    return state.id;
  },
};

const user: Module<UserState, any> = {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};

export default user;
